<?php

namespace App\Http\Controllers\Members\Moonlight;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\MoonlightRepository;
use App\Repositories\AreaRepository;
use Storage;

//零工需求

class IndexController extends Controller
{
    public function __construct()
		{
			$this->middleware('auth:members');
		}
		/**
		*  零工需求翻页列表
		*/
		public function Index(Request $request,MoonlightRepository $MoonlightRepository)
		{
				$user = auth('members')->user();
			 	$pagesize = $request->input('pagesize', '25');
			 	$kw = $request->input('kw', '');
			 	$AreaID=$request->input('AreaID','0');
				$Lng=$request->input('Lng','0');
				$Lat=$request->input('Lat','0');
	 	  
	 	  $result = $MoonlightRepository->GetList($user->ID,$AreaID,$Lat,$Lng,addslashes($kw), [], [], $pagesize, ['Distance' => 'asc']);
		  return response()->json(['code' => 0, 'result' => $result]);
		  
		}
		public function Save(Request $request,MoonlightRepository $MoonlightRepository,AreaRepository $AreaRepository)
		{
			$user = auth('members')->user();
		  $ID=trim($request->input('ID'));
			$data=[
			'Name'=>trim($request->input('Name')),
			'Description'=>trim($request->input('Description')),
			'Money'=>trim($request->input('Money')),
			'Telephone'=>trim($request->input('Telephone')),
			'AreaID'=>trim($request->input('AreaID')),
			'Lat'=>trim($request->input('Lat')),
			'Lng'=>trim($request->input('Lng')),
			];
			 $Area= $AreaRepository->find(trim($request->input('AreaID')));
			 if(!empty($Area))
			 {
			 	 $data['AreaAllID']=$Area->AllID;
			 }
			$data['UpdateTime']=time();
			if ($request->hasFile('file')) {
				$file = $request->file('file');
				$ext = $file->getClientOriginalExtension(); 
				$realPath = $file->getRealPath();  
				$filename = uniqid() . '.' . $ext;
				if (in_array(strtolower($file->extension()), ['jpeg', 'jpg', 'gif', 'gpeg', 'png'])) {
					$bool = Storage::disk('oss')->put("/Moonlight/" . $filename, file_get_contents($realPath));
					if($bool)
					{
					  $data['Picture']=$filename;
					}
				}
			}
			if(empty($ID)  || $ID=='0')
			{
				$data['ID']=$this->nextid();
				$data['MembersID']=$user->ID;
				$data['CreateTime']=time();
				$MoonlightRepository->create($data);
			}else{
				$result=$MoonlightRepository->findBy('ID',$ID);
				if(trim($result->Picture)!='')
				{
						Storage::disk('oss')->delete("/Moonlight/" . $result->Picture);
				}
				$MoonlightRepository->update($data,['ID'=>$ID]);
				}
			 return response()->json(['code' => 0, 'message' =>'保存成功！']);
		}
	 
		public function GetByID(Request $request,MoonlightRepository $MoonlightRepository)
		{
			$ID=$request->input('ID');
			$result=$OddJobRepository->findBy('ID',$ID);
			if(!empty($result))
			{
			 $result->Picture=$result->Picture==''?'':$this->ToImageURL("/Moonlight/".$result->Picture);
			}
	    return response()->json(['code' => 0, 'result' =>$result]);  
		}
		 
}
